package com.ulook.lookplanet.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.qmuiteam.qmui.widget.QMUIRadiusImageView2;
import com.ulook.lookplanet.R;
import com.ulook.lookplanet.base.WidgetData;
import com.ulook.lookplanet.common.AppServer;
import com.ulook.lookplanet.data.model.TCommunity;
import com.ulook.lookplanet.util.ThrowException;
import com.ulook.lookplanet.util.net.AsynRequestUtil;
import com.ulook.lookplanet.util.net.OkHttpException;
import com.ulook.lookplanet.util.net.ResponseCallback;

/**
 * 描述：社区（小组）组件
 *
 * @author L1998
 * @data 2021/4/20
 */
public class CommunityView extends LinearLayout implements WidgetData<TCommunity> {

    private Context context;

    private QMUIRadiusImageView2 imageView;
    private TextView textView;

    private TCommunity community;
    private Bitmap bitmap;

    public CommunityView(Context context) {
        super(context);
        initCommunityView(context);
    }

    public CommunityView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initCommunityView(context);
    }

    public CommunityView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initCommunityView(context);
    }

    private void initCommunityView(Context context){
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.widget_commu_view, this, true);
    }


    @Override
    public void setWidgetData(TCommunity value) {
        this.community = value;

        textView = findViewById(R.id.w_commu_text);
        textView.setText(community.getName());

        imageView = findViewById(R.id.w_commu_img);

        ResponseCallback callback = new ResponseCallback() {
            @Override
            public void onSuccess(Object res) {
                byte[] image = (byte[]) res;
                bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
                imageView.setImageBitmap(bitmap);
            }
            @Override
            public void onFailure(OkHttpException failuer) {
                ThrowException.print(failuer, failuer.getEmsg());
            }
        };
        AsynRequestUtil.loadImg(AppServer.DEFAULT_IMG_PATH + community.getComuimg(), null, callback);
    }

    @Override
    public void setWidgetData(TCommunity value, int currUserID) {
        setWidgetData(value);
    }

    /**
     * 获取小组的image
     * @return
     */
    public Bitmap getCommuImage(){
        return ((BitmapDrawable)imageView.getDrawable()).getBitmap();
    }

    /**
     * 获取小组对象
     */
    public TCommunity getCommunity(){
        return community;
    }

}
